package com.hmjk.health.home;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hmjk.health.HealthApp;
import com.hmjk.health.FocusFragment;
import com.hmjk.health.IndexActivity;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.family.FamilyMemberActivity;
import com.hmjk.health.setting.SettingsConstants;
import com.hmjk.health.user.BuildFamilyDialog;
import com.hmjk.health.user.BuildFamilyDialog.OnFaDialogDismissListener;
import com.hmjk.health.util.FA_DATA;
import com.hmjk.health.util.FMEM_DATA;
import com.hmjk.health.util.MEM_FACE;
import com.hmjk.health.views.RefreshLayout;
import com.hmjk.health.views.RefreshLayout.OnRefreshListener;
import com.hmjk.health.views.RoundImageView;

public class FamilyFragment extends FocusFragment implements OnClickListener{
	private final String TAG = FamilyFragment.class.getSimpleName();

	private HealthApp mApp = null;
	private boolean attached = false;
	
	private LayoutInflater mInflater;
	
	private FA_DATA mCurFA;
	private ImageView scanView;
	private RefreshLayout refresh;
	private String refreshing = null;
	private LinearLayout mTitleBg;
	
	private RelativeLayout mFaNameView;
	private TextView mWelcome;
	private TextView mFaName;
	private ImageView mFaNameArrow;
	private TextView mYouAre;
	
	//selr status
	private TextView mIsCreator;
	private TextView mIsAdmin;
	private TextView mIsMember;
	//private LinearLayout mAdminBox;
	//private ImageView lvIcon1;
	//private ImageView lvIcon2;
	//private TextView mFaToDoNum;
	//private InnerListView mFaToDoList;
	//private TextView mFaToDoEmpty;
	private TextView mMemTitle;
	private LinearLayout mMemRoom;
	private Animation rotateDown;
	private Animation rotateUp;
	private boolean night = false;
	
	private long uptime = 0;
	private ArrayList<FA_DATA> mFaListData = new ArrayList<FA_DATA>();
	private ArrayList<FMEM_DATA> mMemListData = new ArrayList<FMEM_DATA>();
	private ArrayList<FMEM_DATA> mShownMemListData = new ArrayList<FMEM_DATA>();
	//private MemAdapter mMemberListAdapter;
	private String entertype = null;
	
	LinearLayout mSelf;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onAttach(Activity a){
		logd("onAttach");
		super.onAttach(a);
		attached = true;
	}
	
	@Override
	public void onDetach(){
		logd("onDetach");
		attached = false;
		super.onDetach();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
		mApp = (HealthApp)getActivity().getApplication();
		mInflater = inflater;
		View v = inflater.inflate(R.layout.family, container, false);
		entertype = mApp.getEnterType();
		
		scanView = (ImageView) v.findViewById(R.id.scan);
		scanView.setOnClickListener(this);
		
		ImageView ticon = (ImageView) v.findViewById(R.id.title_icon);
		TextView ttext = (TextView) v.findViewById(R.id.title_text);
		
		ImageView setv = (ImageView) v.findViewById(R.id.set);
		setv.setOnClickListener(this);
		if(entertype.equals(IndexActivity.ENTER_HEALTH)){
			ticon.setImageResource(R.drawable.health_logo);
			ttext.setTextColor(getResources().getColor(R.color.FOREGROUND_RED));
			ttext.setText(R.string.health_name);
			scanView.setImageResource(R.drawable.health_scan);
			setv.setImageResource(R.drawable.health_set_icon);
		}
		refresh = (RefreshLayout)v.findViewById(R.id.refresh_root);
		refresh.initScroll();
		
		refresh.setOnRefreshListener(new OnRefreshListener(){

			@Override
			public void onRefresh() {
				refreshing = null;
				boolean ok = mApp.getDataManager().refreshData(DataManager.F_FAMILYLIST);
				if(ok){
					refreshing = new String(DataManager.F_FAMILYLIST);
				}
				
				if(!ok){
					ok = mApp.getDataManager().refreshData(DataManager.F_FAMILYMEMBER);
					if(ok){
						if(refreshing == null)
							refreshing = new String(DataManager.F_FAMILYMEMBER);
						else
							refreshing += ":" + DataManager.F_FAMILYMEMBER;
					}
				}
				
				if(!ok){
					ok = mApp.getDataManager().refreshData(DataManager.F_MEMBERFACE);
					if(ok){
						if(refreshing == null)
							refreshing = new String(DataManager.F_MEMBERFACE);
						else
							refreshing += ":" + DataManager.F_MEMBERFACE;
					}
				}
				
				if(refreshing == null){
					Message m = mhandler.obtainMessage(MSG_CLOSE_REFRESH_VIEW);
					mhandler.sendMessageDelayed(m, 500);
				}
			}
			
		});
		
		mWelcome = (TextView) v.findViewById(R.id.title1);
		mTitleBg = (LinearLayout) v.findViewById(R.id.fa_title_bg);
		mFaNameView = (RelativeLayout) v.findViewById(R.id.title2_view);
		
		mFaName = (TextView) v.findViewById(R.id.title2);
		mFaNameArrow = (ImageView) v.findViewById(R.id.title2_arrow);
		mYouAre = (TextView) v.findViewById(R.id.title3);
		
		mIsCreator = (TextView) v.findViewById(R.id.p_creator);
		mIsAdmin = (TextView) v.findViewById(R.id.p_admin);
		mIsMember = (TextView) v.findViewById(R.id.p_mem);
		
		//mAdminBox = (LinearLayout)v.findViewById(R.id.admin_box);
		//lvIcon1 = (ImageView) mAdminBox.findViewById(R.id.lv_icon1);
		//lvIcon1.setOnClickListener(this);
		//lvIcon2 = (ImageView) mAdminBox.findViewById(R.id.lv_icon2);
		//lvIcon2.setOnClickListener(this);
		//mFaToDoNum = (TextView) mAdminBox.findViewById(R.id.fa_todo_count);
		//mFaToDoNum.setVisibility(View.INVISIBLE);
		//mFaToDoList = (InnerListView)mAdminBox.findViewById(R.id.todo_list);
		//mFaToDoList.setVisibility(View.GONE);
		//mFaToDoEmpty = (TextView)mAdminBox.findViewById(R.id.todoEmpty);
		
		mMemTitle = (TextView)v.findViewById(R.id.member_title);
		mMemTitle.setText(getResources().getString(R.string.fa_members, 0));
		mMemRoom = (LinearLayout)v.findViewById(R.id.member_room);
		rotateDown = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate180down);
		rotateUp = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate180up);
		//mMemberListAdapter = new MemAdapter();
		//mMemList.setAdapter(mMemberListAdapter);
		/*mMemList.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int pos, long id) {
				int size = mShownMemListData.size();
				if(pos < size){
					FMEM_DATA d = mShownMemListData.get(pos);
					logd(d.uid + "clicked");
				}
			}
			
		});*/
		
		mSelf = (LinearLayout)v.findViewById(R.id.self);
		mSelf.setOnClickListener(this);
		
		return v;
	}
	
	private void updateViews(){
		if(!attached)
			return;
		
		if(mTitleBg == null)
			return;
		
		Time t = new Time();
		t.setToNow();
		if(t.hour >= 19){
			night = true;
			mFaNameArrow.setImageResource(R.drawable.drop_icon_w);
			mWelcome.setTextColor(getResources().getColor(R.color.WHITE));
			mFaName.setTextColor(getResources().getColor(R.color.WHITE));
			mYouAre.setTextColor(getResources().getColor(R.color.WHITE));
			mTitleBg.setBackgroundResource(R.drawable.fa_bg_night);
		}else{
			night = false;
			mFaNameArrow.setImageResource(R.drawable.drop_icon);
			mWelcome.setTextColor(getResources().getColor(R.color.FONT_BLACK));
			mFaName.setTextColor(getResources().getColor(R.color.FONT_BLACK));
			mYouAre.setTextColor(getResources().getColor(R.color.FONT_BLACK));
			mTitleBg.setBackgroundResource(R.drawable.fa_bg_day);
		}
		
		if(mFaListData.size() > 0){
			if((mCurFA.name == null) || mCurFA.name.trim().isEmpty()){
				mFaName.setText(R.string.noFaName);
			}else{
				mFaName.setText(mCurFA.name);
			}
			
			mFaNameArrow.clearAnimation();
			if(mFaListData.size() > 1){
				mFaNameView.setOnClickListener(this);
				mFaNameArrow.setVisibility(View.VISIBLE);
			}else{
				mFaNameView.setOnClickListener(null);
				mFaNameArrow.setVisibility(View.INVISIBLE);
			}
			if((mCurFA.status == null) || mCurFA.status.trim().isEmpty()){
				String your = getResources().getString(R.string.you_are,"?");
				mYouAre.setText(your);
			}else{
				String your = getResources().getString(R.string.you_are,mCurFA.status);
				mYouAre.setText(your);
			}
			
			mSelf.setClickable(true);
			if(mCurFA.creator || mCurFA.admin){
				mIsMember.setVisibility(View.GONE);
				if(mCurFA.creator){
					mIsCreator.setVisibility(View.VISIBLE);
				}else {
					mIsCreator.setVisibility(View.GONE);
				}
				if(mCurFA.admin){
					mIsAdmin.setVisibility(View.VISIBLE);
				}else {
					mIsAdmin.setVisibility(View.GONE);
				}
			}else {
				mIsCreator.setVisibility(View.GONE);
				mIsAdmin.setVisibility(View.GONE);
				mIsMember.setVisibility(View.VISIBLE);
			}
		}else{
			mFaNameArrow.clearAnimation();
			mFaNameArrow.setVisibility(View.INVISIBLE);
			mFaNameView.setOnClickListener(null);
			mFaName.setText("");
			mYouAre.setText("");
			mIsCreator.setVisibility(View.GONE);
			mIsAdmin.setVisibility(View.GONE);
			mIsMember.setVisibility(View.GONE);
			mSelf.setClickable(false);
			//mAdminBox.setVisibility(View.GONE);
		}
		
		updateMemberList();
		
		refresh.setUpdateTime(uptime);
	}
	
	private void updateMemberList(){
		int size = mShownMemListData.size();
		mMemTitle.setText(getResources().getString(R.string.fa_members, size));
		mMemRoom.removeAllViews();
		if(size > 0){
			HashMap<String,MEM_FACE> faceMap = (HashMap<String, MEM_FACE>)mApp.getDataManager().checkData(DataManager.F_MEMBERFACE, null);
			
			for(FMEM_DATA d:mShownMemListData){
				View v = mInflater.inflate(R.layout.fa_mem_list_item, null);
				LinearLayout itemView = (LinearLayout) v.findViewById(R.id.itemview);
				RoundImageView icon = (RoundImageView) itemView.findViewById(R.id.mface);
				TextView name = (TextView) itemView.findViewById(R.id.mname);
				TextView status = (TextView) itemView.findViewById(R.id.mstatus);
				TextView lv_creator = (TextView) itemView.findViewById(R.id.lv_creator);
				TextView lv_admin = (TextView) itemView.findViewById(R.id.lv_admin);
				TextView lv_member = (TextView) itemView.findViewById(R.id.lv_mem);
				
				name.setText(d.name);
				status.setText(d.status);
				if((d.creator == false) && (d.admin == false)){
					lv_member.setVisibility(View.VISIBLE);
					lv_creator.setVisibility(View.GONE);
					lv_admin.setVisibility(View.GONE);
				}else{
					lv_member.setVisibility(View.GONE);
					if(d.creator)
						lv_creator.setVisibility(View.VISIBLE);
					else
						lv_creator.setVisibility(View.GONE);
					
					if(d.admin)
						lv_admin.setVisibility(View.VISIBLE);
					else
						lv_admin.setVisibility(View.GONE);
				}
				
				itemView.setTag(d);
				
				MEM_FACE f = null;
				
				if(faceMap != null)
					f = faceMap.get(d.uid);
				
				if((f == null) || (f.bitmap == null) || f.bitmap.isRecycled()){
					logd("MEM_FACE set to default for "+d.uid);
					icon.setImageResource(R.drawable.default_photo);
					icon.setType(RoundImageView.TYPE_RECT);
					icon.setBackgroundResource(R.drawable.photo_gray_bg);
				}else{
					logd("MEM_FACE set to bitmap for "+d.uid);
					icon.setImageBitmap(f.bitmap);
					icon.setType(RoundImageView.TYPE_ROUNDRECT);
					icon.setBackgroundColor(getResources().getColor(R.color.TRANSPARENT));
				}
				
				itemView.setOnClickListener(new View.OnClickListener(){

					@Override
					public void onClick(View v) {
						FMEM_DATA mem_data = (FMEM_DATA) v.getTag();
						logd(mem_data.uid + " clicked");
						openMemberActivity(mem_data);
					}
					
				});
				mMemRoom.addView(v);
			}
		}
		//mMemberListAdapter.notifyDataSetChanged();
	}
	
	private void openMemberActivity(FMEM_DATA mem_data){
		String fid = mCurFA.id;
		String uid = mApp.getUID();
		
		String cuid = null, auid = null;
		if(mCurFA.creator){
			cuid = uid;
		}
		if(mCurFA.admin){
			auid = uid;
		}
		if((cuid == null) || (auid == null)){
			for(FMEM_DATA d:mShownMemListData){
				if(d.fid.equals(mCurFA.id)){
					if(cuid == null){
						if(d.creator){
							cuid = d.uid;
						}
					}
					if(auid == null){
						if(d.admin){
							auid = d.uid;
						}
					}
				}
				if((cuid != null) && (auid != null)){
					break; //got all
				}
			}
		}
		
		Intent i = new Intent(getActivity(), FamilyMemberActivity.class);
		if(auid != null){
			i.putExtra("isadmin", uid.equals(auid));
		}else{
			i.putExtra("isadmin", false);
		}
		i.putExtra("iscreator", uid.equals(cuid));
		
		i.putExtra("fid", fid);
		i.putExtra("cuid", cuid);
		if(auid != null){
			i.putExtra("auid", auid);
		}
		if(mem_data != null){
			i.putExtra("memuid", mem_data.uid);
			i.putExtra("name", mem_data.name);
			i.putExtra("status", mem_data.status);
		}else{
			i.putExtra("memuid", mApp.getUID());
			i.putExtra("name", getResources().getString(R.string.Me));
			i.putExtra("status", mCurFA.status);
		}
		
		i.putExtra("faname", mCurFA.name);
		
		startActivity(i);
	}

	private String[] getUIDS(ArrayList<FMEM_DATA> list){
		if(list == null)
			return null;
		
		int size = list.size();
		if(size == 0)
			return null;
		
		String[] ret = new String[size];
		int pos = 0;
		for(FMEM_DATA d:list){
			ret[pos] = new String(d.uid);
			pos ++;
		}
		return ret;
	}
	
    private void prepareMemberFace(){
    	String[] args = getUIDS(mShownMemListData);
		mApp.getDataManager().setUserData(DataManager.F_MEMBERFACE, args);
    }
	
	private void retrieveFamilyMemberData(){
		if(mFaListData.size() <= 0){
			logd("retrieveFamilyMemberData FaList empty!");
			mMemListData.clear();
			mShownMemListData.clear();
			return;
		}
		JSONObject memjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYMEMBER, null);
		if(memjson != null){
			String mine = mApp.getUID();
			try {
				long t = memjson.getLong("uptime");
				uptime = Math.max(uptime, t);
				JSONArray ar = memjson.getJSONArray("array");
				int len = ar.length();
				mMemListData.clear();
				mShownMemListData.clear();
								
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					FMEM_DATA d = new FMEM_DATA();
					d.uid = e.getString("uid");
					if(mine.equals(d.uid) == false){
						d.fid = e.getString("fid");
						d.name = e.getString("name");	
						d.status = e.getString("status");
						String b = e.getString("build");
						if(b.equals("1")){
							d.creator = true;
						}
						
						String a = e.getString("admin");
						if(a.equals("1")){
							d.admin = true;
						}
						
						mMemListData.add(d);
						if(d.fid.equals(mCurFA.id)){
							mShownMemListData.add(d);
						}
					}
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void retrieveFamilyListData(){
		JSONObject fajson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYLIST, null);
		if(fajson != null){
			try {
				long t = fajson.getLong("uptime");
				uptime = Math.max(uptime, t);
				JSONArray ar = fajson.getJSONArray("array");
				int len = ar.length();
				boolean found = false;
				mFaListData.clear();
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					FA_DATA d = new FA_DATA();
					d.id = e.getString("fid");
					d.name = e.getString("name");
					
					d.status = e.getString("status");
					String b = e.getString("build");
					if(b.equals("1")){
						d.creator = true;
					}
					
					String a = e.getString("admin");
					if(a.equals("1")){
						d.admin = true;
					}
					
					if(mCurFA.id.equals(d.id)){
						found = true;
						mCurFA.name = d.name;
						mCurFA.index = i;
						mCurFA.status = d.status;
						mCurFA.admin = d.admin;
						mCurFA.creator = d.creator;
					}
					mFaListData.add(d);
				}
				if(mFaListData.size() == 0){
					mCurFA.clear();
					SharedPreferences pref = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
					Editor editor = pref.edit();
					editor.putString(SettingsConstants.KEY_FA_FID, "");
					editor.commit();
					retrieveFamilyMemberData();
				}else if(!found){
					FA_DATA first = mFaListData.get(0);
					mCurFA.id = first.id;
					mCurFA.name = first.name;
					mCurFA.index = 0;
					mCurFA.status = first.status;
					mCurFA.admin = first.admin;
					mCurFA.creator = first.creator;
					SharedPreferences pref = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
					Editor editor = pref.edit();
					editor.putString(SettingsConstants.KEY_FA_FID, mCurFA.id);
					editor.commit();
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public FA_DATA getCurFaCopy(){
		if(mCurFA == null)
			return null;
		
		return new FA_DATA(mCurFA);
	}
	
	
	
	public void buildAFamily(boolean force){
		if(force || (mFaListData.size() == 0)){
		BuildFamilyDialog.open(getActivity(), new OnFaDialogDismissListener(){
			@Override
			public void onDismiss(boolean toBeCreate, FA_DATA data) {
				if(toBeCreate && (data != null) && (data.name != null) && (data.name.isEmpty() == false)){
					try{
					JSONObject commit = new JSONObject();
					commit.put("familyname", data.name);
					commit.put("admin", data.admin?"1":"0");
					commit.put("familystatus", data.status);
					commit.put("action", "create");
					boolean ok = mApp.getDataManager().commitData(DataManager.F_FAMILYLIST, commit);
					if(ok){
						mApp.showWaitting(getActivity(), null);
						return;
					}else{
						mApp.showAlertDialog(getActivity(), R.string.build_err);
					}
					}catch(JSONException e){
						e.printStackTrace();
					}
				}
				//((HomeActivity)getActivity()).moveToPre();
			}	
		});
		}
	}
	
	public void quitFamily(){
		String selfString = "";
		if(mCurFA.creator) {
			selfString = getResources().getString(R.string.family_abort_cfm_fa_dissolve, mCurFA.name);
		}else {
			selfString = getResources().getString(R.string.family_abort_cfm_self, mCurFA.name);
		}
		mApp.showConfirmDialog(getActivity(), selfString, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(v.getId() == R.id.alert_but1){
					try {
						JSONObject commit = new JSONObject();
						
						commit.put("action", "quit");
						commit.put("fid", mCurFA.id);
						
						mApp.getDataManager().commitData(DataManager.F_FAMILYLIST, commit);
						mApp.showWaitting(getActivity(), null);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	@Override
	public void setFocused(boolean set){
		logd("setFocused "+set);
		if(set == false){
			cancelRefresh();
		}
		super.setFocused(set);
	}
	
	@Override
	public void onResume(){
		logd("onResume");
		super.onResume();
		SharedPreferences pref = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
		String fid = pref.getString(SettingsConstants.KEY_FA_FID, "");
		mCurFA = new FA_DATA();
		mCurFA.id = fid;
		retrieveFamilyListData();
		retrieveFamilyMemberData();
		
		prepareMemberFace();
		updateViews();
	}

	@Override
	public void onPause(){
		logd("onPause");
		super.onPause();
		//setFocused(false);
	}
	
	@Override
	public void onDestroyView(){
		logd("onDestroyView");
		super.onDestroyView();
	}

	@Override
	public boolean cancelRefresh(){
		refreshing = null;
		if((refresh != null) && refresh.isRefreshing()){
			refresh.stopRefreshing();
			return true;
		}
		return false;
	}
	
	private void updateRefreshFlag(String clear){
		if(refreshing.contains(clear)){
			String[] ss = refreshing.split(":");
			String flag = "";
			for(String s:ss){
				if(s.equalsIgnoreCase(clear) == false){
					if(flag.equals("") == false){
						flag += ":";
					}
					flag += s;
				}
			}
			if(flag.trim().isEmpty())
				refreshing = null;
			else{
				refreshing = flag.trim();
			}
		}
	}
	
	public void dataUpdate(Intent i){
		if(mApp == null)
			return;
		
		String action = i.getAction();
		if(action.equals(DataManager.DATA_UPDATE_ACTION)){
			String t = i.getStringExtra("type");
			boolean s = i.getBooleanExtra("state", false);
			logd("dataUpdate:"+t+";"+s);
			if(t.equals(DataManager.F_FAMILYLIST) || t.equals(DataManager.F_FAMILYMEMBER) || t.equals(DataManager.F_MEMBERFACE)){
				if(refreshing != null){
					updateRefreshFlag(t);
					if(s && t.equals(DataManager.F_FAMILYLIST)){
						retrieveFamilyListData();
						mApp.getDataManager().setUserData(DataManager.F_FAMILYMEMBER, null);
						boolean ok = mApp.getDataManager().refreshData(DataManager.F_FAMILYMEMBER);
						if(ok){
							if(refreshing == null)
								refreshing = new String(DataManager.F_FAMILYMEMBER);
							else
								refreshing += ":" + DataManager.F_FAMILYMEMBER;
						}
					}else if(s && t.equals(DataManager.F_FAMILYMEMBER)){
						retrieveFamilyMemberData();
						String[] args = getUIDS(mShownMemListData);
						mApp.getDataManager().setUserData(DataManager.F_MEMBERFACE, args);
						boolean ok = mApp.getDataManager().refreshData(DataManager.F_MEMBERFACE);
						if(ok){
							if(refreshing == null)
								refreshing = new String(DataManager.F_MEMBERFACE);
							else
								refreshing += ":" + DataManager.F_MEMBERFACE;
						}
					}
					if(refreshing == null){
						cancelRefresh();
						updateViews();
					}
				}else if(s){
					if(s && t.equals(DataManager.F_FAMILYLIST)){
						retrieveFamilyListData();
						retrieveFamilyMemberData();
					}else if(s && t.equals(DataManager.F_FAMILYMEMBER)){
						retrieveFamilyMemberData();
					}
					updateViews();
				}
			}
		}else if(action.equals(DataManager.DATA_COMMIT_RESULT)){//build new fa ok
			String t = i.getStringExtra("type");
			if(t.equals(DataManager.F_FAMILYLIST)){
				String act = i.getStringExtra("action");
				String state = i.getStringExtra("state");
				int code = i.getIntExtra("code", 400);
				mApp.dismissWaiting();
				if(act.equalsIgnoreCase("create")){
					if(code != 200){
						mApp.showAlertDialog(getActivity(), R.string.build_err);
					}else if(state.equals("00") == false){
						mApp.showAlertDialog(getActivity(), R.string.build_err);
					}else{
						String fid = i.getStringExtra("fid");
						mCurFA.id = fid;
						SharedPreferences pref = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
						Editor editor = pref.edit();
						editor.putString(SettingsConstants.KEY_FA_FID, mCurFA.id);
						editor.commit();
						retrieveFamilyListData();
						retrieveFamilyMemberData();
						updateViews();
					}
				}else if(act.equalsIgnoreCase("quit")){
					if((code == 200) && (state.equals("00") == true)){
						try {
							JSONObject commit = new JSONObject();
							commit.put("cmd", "quit");
							String fid = i.getStringExtra("fid");
							commit.put("fid", fid);
							mApp.getDataManager().commitData(DataManager.F_FAMILYMEMBER, commit);
							
							retrieveFamilyListData();
							retrieveFamilyMemberData();
							updateViews();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}	
					}else {
						mApp.showAlertDialog(getActivity(), R.string.commit_err);
					}
				}
			}
		}
	}
	
	private final int MSG_CLOSE_REFRESH_VIEW = 211;
	//private final int MSG_CLOSE_INFO_WIN = 212;
	
	private Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_CLOSE_REFRESH_VIEW:{
				cancelRefresh();
			}
			break;
			/*case MSG_CLOSE_INFO_WIN:{
				closeInfoWin();
			}
			break;*/
			}
		}
	};
	
	/*private PopupWindow infoWin = null;
	private View infoView = null;
	private void closeInfoWin(){
		if((infoWin != null) && infoWin.isShowing()){
			mhandler.removeMessages(MSG_CLOSE_INFO_WIN);
			infoWin.dismiss();
		}
	}
	
	private void showPopInfo(String show, View anchor){
		if((infoWin != null) && infoWin.isShowing()){
			mhandler.removeMessages(MSG_CLOSE_INFO_WIN);
			infoWin.dismiss();
		}else{
			if(infoWin == null){
				infoView = mInflater.inflate(R.layout.pop_text_info, null);
				infoWin = new PopupWindow(infoView,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
				infoWin.setTouchable(true);
				infoWin.setBackgroundDrawable(new ColorDrawable(0x00000000));
				infoWin.setOnDismissListener(new PopupWindow.OnDismissListener(){
	
					@Override
					public void onDismiss() {
						infoWin = null;
						infoView = null;
					}
					
				});
			}
		
			TextView tv = (TextView) infoView.findViewById(R.id.pop_info);
			tv.setText(show);
			infoWin.showAsDropDown(anchor);
			mhandler.removeMessages(MSG_CLOSE_INFO_WIN);
			Message m = mhandler.obtainMessage(MSG_CLOSE_INFO_WIN);
			mhandler.sendMessageDelayed(m, 2 * 1000);
		}
	}*/
	
	private PopupWindow familyPopWin = null;
	private ImageView arrow = null;
	private View familyView = null;
	private FaListAdapter mFaListAdapter = null;
	private void showFamilyPopWin(){
		float density = getResources().getDisplayMetrics().density;
		int w = mFaNameView.getMeasuredWidth();
		int h = mFaNameView.getMeasuredHeight();
		int p = (int) (8 * density);
		
		if(familyPopWin == null){
			
			familyView = mInflater.inflate(R.layout.fa_family_pop_win, null);
			if(night){
				familyView.setBackgroundResource(R.drawable.fm_pop_bg_night);
			}else{
				familyView.setBackgroundResource(R.drawable.fm_pop_bg_day);
			}
			familyPopWin = new PopupWindow(familyView,w+p+p, h * 5, true);
			familyPopWin.setTouchable(true);
			familyPopWin.setBackgroundDrawable(new ColorDrawable(0x00000000));
			
			familyPopWin.setOnDismissListener(new PopupWindow.OnDismissListener(){
				@Override
				public void onDismiss() {
					familyPopWin = null;
					familyView = null;
					//arrow.startAnimation(rotateUp);
					mFaNameArrow.startAnimation(rotateUp);
				}
				
			});
		}
		TextView title = (TextView)familyView.findViewById(R.id.title);
		if(mCurFA.name.trim().isEmpty())
			title.setText(R.string.noFaName);
		else
			title.setText(mCurFA.name);
		arrow = (ImageView)familyView.findViewById(R.id.title_arrow);
		if(night){
			title.setTextColor(0xffffffff);
			arrow.setImageResource(R.drawable.drop_icon_w);
		}else{
			title.setTextColor(0xff444444);
			arrow.setImageResource(R.drawable.drop_icon);
		}
		
		ListView list = (ListView)familyView.findViewById(R.id.faPopList);
		if(mFaListAdapter == null)
			mFaListAdapter = new FaListAdapter();
		list.setAdapter(mFaListAdapter);
		list.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int pos, long id) {
				FaListAdapter.ViewHolder h = (FaListAdapter.ViewHolder)v.getTag();
				if(h.fid.equals(mCurFA.id) == false){
					int i = 0;
					for(FA_DATA d:mFaListData){
						if(d.id.equals(h.fid)){
							mCurFA.name = d.name;
							mCurFA.index = i;
							mCurFA.status = d.status;
							mCurFA.admin = d.admin;
							mCurFA.creator = d.creator;
							mCurFA.id = d.id;
							SharedPreferences pref = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
							Editor editor = pref.edit();
							editor.putString(SettingsConstants.KEY_FA_FID, mCurFA.id);
							editor.commit();
							break;
						}
						i++;
					}
					retrieveFamilyMemberData();
					updateViews();
				}
				familyPopWin.dismiss();
			}
			
		});
		mFaNameArrow.startAnimation(rotateDown);
		arrow.startAnimation(rotateDown);
		familyPopWin.showAsDropDown(mFaNameView, -p, -h);
	}
	
	class FaListAdapter extends BaseAdapter{
		class ViewHolder{
			public TextView item;
			public String fid;
		}
		@Override
		public int getCount() {
			return mFaListData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int pos, View itemView, ViewGroup group) {
			ViewHolder holder;
			if(itemView == null){
				itemView = mInflater.inflate(R.layout.fa_pop_mid_item, null);
				
				holder = new ViewHolder();
				holder.item = (TextView) itemView.findViewById(R.id.fa_pop_item_name);
				if(night){
					itemView.setBackgroundResource(R.drawable.normal_click_bg);
					holder.item.setTextColor(0xffffffff);
				}else{
					itemView.setBackgroundResource(R.drawable.normal_click_bg);
					holder.item.setTextColor(0xff444444);
				}
				itemView.setTag(holder);
			}else{
				holder = (ViewHolder) itemView.getTag();
			}
			
			FA_DATA d = mFaListData.get(pos);
			if(d.name.trim().isEmpty())
				holder.item.setText(R.string.noFaName);
			else
				holder.item.setText(d.name);
			holder.fid = new String(d.id);
			return itemView;
		}
		
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.scan:{
			((BaseHomeActions)getActivity()).openPopMenu("family",scanView);
		}
		break;
		case R.id.set:{
			if(mCurFA.creator){
				((BaseHomeActions)getActivity()).openSettings("familycreator", mCurFA.id);
			}else {
				((BaseHomeActions)getActivity()).openSettings("family", mCurFA.id);
			}
		}
		break;
		case R.id.title2_view:{
			showFamilyPopWin();
		}
		break;
		case R.id.self:{
			openMemberActivity(null);
		}
		break;
		/*case R.id.lv_icon1:
		case R.id.lv_icon2:{
			String show = (String) v.getTag();
			showPopInfo(show, v);
		}
		break;*/
		}
	}
}
